/**
 * 手势事件管理
 * @param {Object} options
 * @param {Boolean} preventDefault
 * @param {Boolean} stopPropagation
 *
 * @events:
 *     ontouchstart
 *     ontouchmove
 *     ontouchend
 *     ontap
 *     onswipeleft
 *     onswiperight
 *     onswipeup
 *     onswipedown
 *
 * @example
 * <div id="element"></div>
 *
 * var touch = new h5.Touch(element);
 * touch.ontap = function() {
 *
 * }
 *
 */
var b = navigator.userAgent.toLowerCase();
browser = {
	safari : /webkit/.test(b),
	opera : /opera/.test(b),
	msie : /msie/.test(b) && !/opera/.test(b),
	mozilla : /mozilla/.test(b) && !/compatible/.test(b),
	winphone: window.navigator.msPointerEnabled
};
var h5 = {}
h5.Touch = function(element, preventDefault, stopPropagation) {
	this._element = element;
	this._preventDefault = preventDefault;
	this._stopPropagation = stopPropagation;

	this._startX = 0;
	this._startY = 0;
	this._istouch = false;

	if(h5.Touch.support) {
		element.addEventListener('touchstart', this, false);
		element.addEventListener('touchmove', this, false);
		element.addEventListener('touchend', this, false);
	} else if(browser.winphone) {
		var self = this;
		element.addEventListener('MSPointerDown', function(e) {			
			self.handleEvent(e, self);
		}, true);
		element.addEventListener('MSPointerMove', function(e) {
			self.handleEvent(e, self);
		}, true);
		element.addEventListener('MSPointerUp', function(e) {
			self.handleEvent(e, self);
		}, true);
		element.addEventListener('MSPointerCancel', function(e) {
			self.handleEvent(e, self);
		}, true);
	} else if(browser.msie) {
		var self = this;
		element.attachEvent('onmousedown', function(e) {
			self.handleEvent(e, self);
		}, true);
		element.attachEvent('onmousemove', function(e) {
			self.handleEvent(e, self);
		}, true);
		element.attachEvent('onmouseup', function(e) {
			self.handleEvent(e, self);
		}, true);
	} else {
		element.addEventListener('mousedown', this, false);
		element.addEventListener('mousemove', this, false);
		element.addEventListener('mouseup', this, false);
	}
}

h5.Touch.tapDistance = 20;
h5.Touch.swipeDistance = 100;

h5.Touch.support = ( typeof window.TouchEvent != 'undefined') && (window.navigator.userAgent.indexOf('Mobile') > -1);

/*
 * 初始化并注册事件,多次绑定会有多次事件监听器响应
 */
h5.Touch.tap = function(element, fn, preventDefault, stopPropagation) {
	if( typeof element == 'string') {
		element = document.getElementById(element);
	}
	// var ele = new h5.Touch(element);
	// ele.ontap = null;
	// ele.ontap = fn;
	new h5.Touch(element, preventDefault, stopPropagation).ontap = fn;
}

h5.Touch.prototype = {
	handleEvent : function(e, self) {
		//不是IE浏览器则把当前对象赋值给self
		if(!browser.msie)
			self = this;	
		var testtxt=$('#test');	
		// /*
		// 如果存在changedTouches数组，则使用它，否则使用eventObject创建一组 stz++
    	var touchPoints = (typeof e.changedTouches != 'undefined') ? e.changedTouches : [e];
    	//testtxt.text(testtxt.text()+touchPoints.length);		
		var touchPoint = touchPoints[0];
        // 获取唯一的touchPoint id，如果不存在，则使用1作为默认值
        
        var touchPointId = (typeof touchPoint.identifier != 'undefined') ? touchPoint.identifier : (typeof touchPoint.pointerId != 'undefined') ? touchPoint.pointerId : 1;
        if (e.type.match(/(down|start)$/i)) {
            // 处理mousedown, MSPointerDown,以及touchstart事件
            // testtxt.text(testtxt.text()+e.pageY);
            self._touchstart(touchPoint);
        }
        else if (e.type.match(/move$/i)) {
            // 处理mousemove, MSPointerMove,以及touchmove事件
            //testtxt.text(testtxt.text()+e.pageY);
            self._touchmove(touchPoint);
        }
        else if (e.type.match(/(up|end)$/i)) {
            // 处理mouseup, MSPointerUp,以及touchend事件
            self._touchend(touchPoint); //移动一段距离后不触发..winphone上不行  win8可以
        }
        else if (e.type=='MSPointerCancel') { // MSPointerCancel stz
            //testtxt.text(e.type+', '+e.pageY);
            //self._touchendForWP(touchPoint); 
            self._touchend(touchPoint);
        }
        // */
	    /*
		//判断鼠标事件的类型
		switch (e.type) {
			case 'touchstart':
				self._touchstart(e.targetTouches[0]);
				break;
			case 'touchmove':
				self._touchmove(e.changedTouches[0]);
				break;
			case 'touchend':
				testtxt.text(testtxt.text()+'|touchend');	
				self._touchend(e.changedTouches[0]);
				break;
			case 'mousedown':
				self._touchstart(e);
				break;
			case 'mousemove':
				self._touchmove(e);
				break;
			case 'mouseup':
				testtxt.text(testtxt.text()+'|mouseup');	
				self._touchend(e);
				break;
			case 'MSPointerDown':
				self._touchstart(e);
				break;
			case 'MSPointerMove':
				self._touchmove(e);
				break;
			case 'MSPointerUp':
				// testtxt.text(testtxt.text()+'|MSPointerUp');	
				//self._touchend(e); //移动一段距离后不触发..winphone上不行  win8可以
				break;
		}
		*/
		//获取触发事件的源标签 --下面调整到上面
		var tagName = '';
		if(e.target != undefined)
			tagName = e.target.tagName;
		else
			tagName = e.srcElement.tagName;
		//文本，下拉框，输入框则阻止事件传递
		if(/SELECT|TEXTAREA|INPUT/.test(tagName.toUpperCase()) || self._stopPropagation) {
			//e.stopPropagation();
			if(e.stopPropagation){
				e.stopPropagation();
			}else if(browser.msie||browser.winphone) {
				e.cancelBubble = true;
				//return false;
			}
		}
		
		if(self._preventDefault) {
			// 阻止拖动和缩放使得绘图能够正常进行 stz+ 9
		    if(e.preventDefault){
				e.preventDefault();
			}else if (e.preventManipulation){
		    	e.preventManipulation();
		    }else if(browser.msie||browser.winphone) {
				e.returnValue = false;
				//return false;
			}
		}
		
	},
	_touchstart : function(e) {
		this._istouch = true;
		this._startX = e.pageX ? e.pageX : e.clientX;
		this._startY = e.pageY ? e.pageY : e.clientY;

		this.ontouchstart(e);
		//document.body.className="msTouchAction";
		this._element.parentNode.className = this._element.parentNode.className + " msTouchAction";
	},
	_touchmove : function(e) {
		if(this._istouch) {
			if (!(this._startX == e.pageX && this._startY == e.pageY)) { //要有移动才触发stz
				this.ontouchmove(e);
			}
		}
	},
	_touchend : function(e) {
		//document.body.className="";
		if ((this._startX == e.pageX || this._startY == e.pageY)) {
			return;
		}
		this._element.parentNode.className = this._element.parentNode.className.replace("msTouchAction", "")
		var pageX = e.pageX ? e.pageX : e.clientX, //当前鼠标X位置
		pageY = e.pageY ? e.pageY : e.clientY, //
		deltaX = pageX - this._startX, //X轴位置移动的距离

		deltaY = pageY - this._startY, //
		tapDistance = h5.Touch.tapDistance, //
		swipeDistance = h5.Touch.swipeDistance;
		this._istouch = false;
		this.ontouchend(e);
		if(Math.abs(deltaX) < tapDistance && Math.abs(deltaY) < tapDistance) {
			this.ontap(e);
		} else {
			if(deltaX >= swipeDistance) {
				this.onswiperight(e);
			} else if(deltaX <= -swipeDistance) {
				this.onswipeleft(e);
			}

			if(deltaY >= swipeDistance) {
				this.onswipedown(e);
			} else if(deltaY <= -swipeDistance) {
				this.onswipeup(e);
			}
		}
	},
	/**
	 * events
	 */
	ontouchstart : function(pageX, pageY) {

	},
	ontouchmove : function(pageX, pageY) {

	},
	ontouchend : function(pageX, pageY) {

	},
	ontap : function() {

	},
	onswipeleft : function() {

	},
	onswiperight : function() {

	},
	onswipeup : function() {

	},
	onswipedown : function() {

	},
	/*
	 *
	 */
	getElement : function() {
		return this._element;
	}
}

h5.Touch.prototype.constructor = h5.Touch;
